package bom.example.common.filter;

import bom.example.common.session.SessionProvider;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.annotation.Annotation;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author X.I.O
 * @title: Interceptor
 * @projectName demo
 * @description: TODO
 * @date 2021/11/12 10:38
 */
@Component
@Slf4j
@Order(0)
public class Interceptor extends HandlerInterceptorAdapter {

    private final transient ReentrantLock lock = new ReentrantLock();

    @Autowired
    private SessionProvider sessionProvider;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        final ReentrantLock lock = this.lock;
        lock.lock();
        try {
            Object lastOpeTimeObj = sessionProvider.getAttribute(request, "lastOperateTime");
            System.out.println("全局拦截2");
            log.info("这是全局拦截2=======>"+new Date());
            if(lastOpeTimeObj!=null){
                Date date=(Date) lastOpeTimeObj;
                SimpleDateFormat dft=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                log.info("上次操作时间: "+dft.format(date));
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
        if(handler instanceof HandlerMethod){
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            ApiOperation annotation = handlerMethod.getMethodAnnotation(ApiOperation.class);
            if(annotation!=null){
                log.info("这是拦截器2："+annotation.value());
            }
        }
        return true;
    }

}
